import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

# 1. 读取并准备数据
# 定义特征名称
feature_names = [
    "Alcohol", "Malic_acid", "Ash", "Alcalinity_of_ash", "Magnesium",
    "Total_phenols", "Flavanoids", "Nonflavanoid_phenols", "Proanthocyanins",
    "Color_intensity", "Hue", "OD280/OD315_of_diluted_wines", "Proline"
]

# 1.读取数据（假设已下载到本地）
# 如果未下载，可以使用urllib库从URL直接读取
try:
    # 尝试从本地文件读取
    data = pd.read_csv("wine.data", header=None, names=["class"] + feature_names)
except FileNotFoundError:
    # 从UCI网站直接读取
    import urllib.request
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data"
    response = urllib.request.urlopen(url)
    data = pd.read_csv(response, header=None, names=["class"] + feature_names)

# 2.筛选类别1和2的数据
#提取class为1类和2类的数据
binary_data = data[data["class"].isin([1, 2])]
print(f"筛选后的数据集大小: {binary_data.shape}")
print(f"类别1的样本数: {sum(binary_data['class'] == 1)}")
print(f"类别2的样本数: {sum(binary_data['class'] == 2)}")

# 分离特征和标签
X = binary_data[feature_names].values
y = binary_data["class"].values

# 数据标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 2. 执行PCA降维到2维
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

# 输出PCA结果
print("\nPCA降维结果:")
print(f"主成分方差贡献率: {pca.explained_variance_ratio_}")
print(f"累计方差贡献率: {sum(pca.explained_variance_ratio_):.4f}")
print("\nPCA降维后的两维特征（前10个样本）:")
pca_results = pd.DataFrame(X_pca[:10], columns=['PC1', 'PC2'])
print(pca_results)

# 3. 执行LDA降维
lda = LinearDiscriminantAnalysis(n_components=1)  # 二类问题最多降维到1维
X_lda = lda.fit_transform(X_scaled, y)

# 输出LDA结果
print("\nLDA降维结果:")
print(f"LDA分类准确率: {lda.score(X_scaled, y):.4f}")
print("LDA降维后的特征（前10个样本）:")
lda_results = pd.DataFrame(X_lda[:10], columns=['LD1'])
print(lda_results)

# 4. 输出所有样本的PCA两维特征
print("\n所有样本的PCA两维特征:")
all_pca_results = pd.DataFrame(X_pca, columns=['PC1', 'PC2'])
all_pca_results['class'] = y  # 添加类别标签以便分析
print(all_pca_results)

# 可选择保存结果到CSV文件
all_pca_results.to_csv('wine_pca_results.csv', index=False)
print("\nPCA结果已保存到wine_pca_results.csv文件")
